<template>
  <!-- 搜索页面 -->
  <div class="Search">
    <div class="top">
      <img @click="$router.back()" class="back" src="@/assets/img/icons/black/back.svg" />
      <div class="box">
        <img class="s" src="@/assets/img/icons/search.svg" />
        <input @input="input" v-model="value" type="text" placeholder="输入书名、作者名" />
        <img v-if="value" class="x" src="@/assets/img/icons/cls.svg" @click="value = ''" />
        <div v-if="!value" class="x"></div>
      </div>
      <div class="btn" @click="searchClick">搜索</div>
      <k-scroll class="scroll" v-if="value && imagineWords.length" topColor="#efefef" bottomColor="#efefef" topType="stretch" bottomType="stretch">
        <div class="imagine" :style="{ height: imagineWords.length ? 'auto' : '100%' }">
          <div class="item" v-for="(item, index) in imagineWords" :key="JSON.stringify(item) + index" @click="imagineWordsClick(item)">
            {{ item }}
          </div>
        </div>
      </k-scroll>
    </div>
    <k-scroll
      class="scroll"
      topColor="var(--main-background-color)"
      bottomColor="var(--main-background-color)"
      topType="stretch"
      bottomType="load"
      :isnomore="true"
    >
      <div class="content">
        <div v-if="searchHistory" class="history">
          <div class="top1">
            <div class="title">搜索历史</div>
            <div class="clear" @click="clearHistory">
              <img src="@/assets/img/icons/delete.svg" />
              <span>清空记录</span>
            </div>
          </div>
          <div class="box">
            <div class="item" v-for="item in searchHistory" :key="JSON.stringify(item)" @click="historyClick(item)">{{ item }}</div>
          </div>
        </div>
        <div class="hotwords">
          <div class="top1">
            <div class="title">大家都在搜</div>
            <div class="refresh" @click="getHotWords">
              <span>换一批</span>
              <img :style="{ transform: 'rotate(' + rotate + 'deg)' }" src="@/assets/img/icons/refresh.svg" />
            </div>
          </div>
          <div class="box">
            <div class="item" v-for="item in hotwords" :key="JSON.stringify(item)" @click="hotWordsClick(item.searchcontext)">
              <span>{{ item.searchcontext.length > 5 ? item.searchcontext.slice(0, 5) : item.searchcontext }}</span>
            </div>
          </div>
        </div>
        <div class="yourlike">
          <div class="top1">
            <img src="@/assets/img/icons/love.svg" />
            <span>猜你喜欢</span>
          </div>
          <div class="item" v-for="item in hotNovels" :key="JSON.stringify(item)" @click="novelClick(item.noveltable)">
            <img v-lazy="item.img" />
            <div class="info">
              <div class="name">{{ item.name }}</div>
              <div class="introduce">{{ item.introduce }}</div>
              <div class="bottom">
                <div class="left">
                  <span>{{ item.type }}</span>
                  <span>|</span>
                  <span>{{ item.author }}</span>
                </div>
                <div class="rate">{{ item.rate.toFixed(1) }}分</div>
              </div>
            </div>
          </div>
        </div>
      </div>
    </k-scroll>
  </div>
</template>

<script>
export default {
  name: 'Search',
  //组件挂载完成
  mounted() {
    this.getHotWords() //获取搜索热词
    this.getHotNovels() //获取搜索小说
    //读取搜索记录缓存
    if (localStorage.getItem('searchHistory')) {
      this.searchHistory = JSON.parse(localStorage.getItem('searchHistory')).reverse()
    }
  },
  //组件激活
  activated() {
    //读取搜索记录缓存
    if (localStorage.getItem('searchHistory')) {
      this.searchHistory = JSON.parse(localStorage.getItem('searchHistory')).reverse()
    }
  },
  data() {
    return {
      //搜索历史
      searchHistory: null,
      //热门搜索词汇
      hotwords: [],
      //热门搜索小说
      hotNovels: [],
      //控制刷新图标转动
      rotate: 0,
      //输入的搜索内容
      value: '',
      //搜索猜想词汇
      imagineWords: [],
    }
  },
  methods: {
    //搜索内容提交
    submitSearchContext(value) {
      this.$network
        .main('searchContext', value)
        .then((data) => {
          console.log('搜索内容提交成功')
        })
        .catch((err) => {
          console.log('搜索内容提交失败:' + err)
        })
    },
    //小说被点击提交
    submitClickNovel(table) {
      this.$network
        .main('clickNovel', table)
        .then((data) => {
          console.log('小说点击记录成功')
        })
        .catch((err) => {
          console.log('小说点击记录失败:' + err)
        })
    },
    //输入框输入事件
    input() {
      this.value = this.value.replace(/\s|[\r\n]/g, '') //删除空格
      //请求联想词汇列表
      if (this.value) {
        this.imagineWords = []
        this.$network
          .main('getImagineWords', this.value)
          .then((data) => {
            for (let item of data) {
              this.imagineWords.push(item.name)
            }
          })
          .catch((err) => {
            this.$toast({
              type: 'fail',
              message: '网络出错！',
            })
          })
      }
    },
    //进入搜索联想词汇
    imagineWordsClick(value) {
      this.$router.push({
        path: '/searchResult',
        query: {
          search: value,
        },
      })
      this.submitSearchContext(value)
    },
    //获取热门搜索词汇
    getHotWords() {
      this.$toast({
        type: 'loading',
        duration: 0,
        message: '刷新中...',
        forbidClick: true,
      })
      this.rotate += 360 //转动
      this.$network
        .main('postNull', 'getHotWords')
        .then((data) => {
          this.hotwords = data
          this.$toast.clear()
        })
        .catch((err) => {
          this.$dialog({
            message: err,
          })
        })
    },
    //获取热门搜索小说
    getHotNovels() {
      this.$network
        .main('postNull', 'getHotNovels')
        .then((data) => {
          this.hotNovels = data
        })
        .catch((err) => {
          this.$dialog({
            message: err,
          })
        })
    },
    //记录历史搜索记录
    recordHistory(value) {
      //记录历史搜索记录
      if (localStorage.getItem('searchHistory')) {
        let a = JSON.parse(localStorage.getItem('searchHistory'))
        for (let i in a) {
          if (a[i] == value) {
            a.splice(i, 1)
            a.push(value)
            localStorage.setItem('searchHistory', JSON.stringify(a))
            break
          }
          if (i == a.length - 1) {
            a.push(value)
            if (a.length >= 7) {
              a.splice(0, a.length - 6)
            }
            localStorage.setItem('searchHistory', JSON.stringify(a))
          }
        }
      } else {
        let a = [value]
        localStorage.setItem('searchHistory', JSON.stringify(a))
      }
    },
    //提示询问是否确定清空历史记录
    clearHistory() {
      this.$dialog({
        message: '确定删除所有搜索历史？',
        showCancelButton: true,
      }).then(() => {
        localStorage.removeItem('searchHistory')
        this.searchHistory = null
      })
    },
    //搜索按钮被点击
    searchClick() {
      this.value = this.value.replace(/ /g, '') //删除所有空格
      if (!this.value) {
        this.$dialog({
          message: '搜索内容不能为空！',
        })
        return
      }
      this.recordHistory(this.value) //记录搜索历史
      this.submitSearchContext(this.value)

      //进入搜索结果页面
      this.$router.push({
        path: '/searchResult',
        query: {
          search: this.value,
        },
      })
    },
    //历史搜索被点击
    historyClick(value) {
      this.recordHistory(value) //记录搜索历史
      //进入搜索结果页面
      this.$router.push({
        path: '/searchResult',
        query: {
          search: value,
        },
      })
      this.submitSearchContext(value)
    },
    //大家都在搜的词被点击
    hotWordsClick(value) {
      this.recordHistory(value) //记录搜索历史
      //进入搜索结果页面
      this.$router.push({
        path: '/searchResult',
        query: {
          search: value,
        },
      })
      this.submitSearchContext(value)
    },
    //热门小说被点击
    novelClick(table) {
      //进入小说阅读页面
      this.$router.push({
        path: '/read',
        query: {
          table,
        },
      })
      this.submitClickNovel(table)
    },
  },
}
</script>

<style src="./index.less" lang='less' scoped></style>
